<template>
  <div 
    class="rounded-full flex items-center justify-center text-gray-700 font-semibold"
    :class="[sizeClass, { 'cursor-pointer': clickable }]"
    @click="handleClick"
    :role="clickable ? 'button' : undefined"
    :aria-label="clickable ? `查看${username || '用户'}的个人资料` : undefined"
    :tabindex="clickable ? 0 : undefined"
  >
    <img 
      v-if="avatar && !imageError && !isEmojiAvatar" 
      :src="fullAvatarUrl"
      class="h-full w-full rounded-full object-cover"
      @error="handleImageError"
      :alt="`${username || '用户'}的头像`"
    />
    <div 
      v-else-if="isEmojiAvatar" 
      class="h-full w-full rounded-full bg-gray-100 flex items-center justify-center"
      :title="`Emoji头像: ${emojiContent}`"
      aria-hidden="true"
    >
      <span :class="emojiSizeClass">{{ emojiContent }}</span>
    </div>
    <template v-else>{{ username ? username[0].toUpperCase() : fallback }}</template>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router';

interface Props {
  username?: string;
  avatar?: string;
  userId?: string;
  size?: 'sm' | 'md' | 'lg' | 'xl';
  clickable?: boolean;
  fallback?: string;
}

const props = withDefaults(defineProps<Props>(), {
  username: '',
  avatar: '',
  userId: '',
  size: 'md',
  clickable: false,
  fallback: '?'
});

const router = useRouter();
const imageError = ref(false);

// 判断是否为Emoji头像
const isEmojiAvatar = computed(() => {
  const hasAvatar = !!props.avatar;
  const isEmoji = hasAvatar && props.avatar.startsWith('emoji:');
  console.log(`Avatar: ${props.avatar}, isEmoji: ${isEmoji}`);
  return isEmoji;
});

// 获取Emoji内容
const emojiContent = computed(() => {
  if (!isEmojiAvatar.value) return '';
  const emoji = props.avatar.replace('emoji:', '');
  console.log(`Emoji content: ${emoji}`);
  return emoji;
});

// 处理图片加载错误
function handleImageError() {
  console.error('头像加载失败:', props.avatar);
  imageError.value = true;
}

// 构建完整的头像URL
const fullAvatarUrl = computed(() => {
  if (!props.avatar) return '';
  
  // 如果是完整URL，直接返回
  if (props.avatar.startsWith('http')) {
    return props.avatar;
  }
  
  // 如果是Emoji头像，不需要处理
  if (props.avatar.startsWith('emoji:')) {
    return '';
  }
  
  // 如果是相对路径，添加后端基础URL
  return `http://localhost:5000${props.avatar}`;
});

// 根据size属性返回不同的尺寸类
const sizeClass = computed(() => {
  const sizes = {
    sm: 'h-8 w-8 bg-gray-300',
    md: 'h-10 w-10 bg-gray-300',
    lg: 'h-16 w-16 bg-gray-300',
    xl: 'h-28 w-28 bg-white p-1 shadow-md'
  };
  return sizes[props.size];
});

// Emoji头像尺寸
const emojiSizeClass = computed(() => {
  const sizes = {
    sm: 'text-lg',
    md: 'text-xl',
    lg: 'text-3xl',
    xl: 'text-5xl'
  };
  return sizes[props.size];
});

// 点击头像
function handleClick() {
  if (props.clickable && props.userId) {
    // 当userId是'me'时，跳转到自己的个人资料页面
    if (props.userId === 'me') {
      router.push('/profile/me');
    } else {
      router.push(`/profile/${props.userId}`);
    }
  }
}

// 监听avatar属性变化
watch(() => props.avatar, (newVal) => {
  if (newVal) {
    console.log('头像已更新:', newVal, '是否为Emoji:', newVal.startsWith('emoji:'));
    // 重置加载错误状态
    imageError.value = false;
  }
});

// 初始化
onMounted(() => {
  console.log('UserAvatar组件挂载, 头像:', props.avatar);
  
  if (props.avatar && !props.avatar.startsWith('emoji:')) {
    const img = new Image();
    img.src = fullAvatarUrl.value;
    img.onerror = handleImageError;
  }
});
</script> 